//
//  AddNewConsigneeAddressViewController.m
//  ChineseCollegeStudentsNetwork
//
//  Created by LeGuo on 5/26/18.
//  Copyright © 2018 刘喆. All rights reserved.
//

#import "AddNewConsigneeAddressViewController.h"
#import "AddNewAddressOptionTableViewCell.h"
#import "JYAddressPicker.h"

#define OPTION_HEIGHT 50.0f

@interface AddNewConsigneeAddressViewController ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) UITableView *infoListView;

@property(nonatomic, strong, readonly) NSArray<NSString *> *options;
@property (nonatomic, strong) NSArray *selectedArr;

@end

@implementation AddNewConsigneeAddressViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWithRGB(245, 245, 245);
    
    if (_model) {
        self.navigationItem.title = @"编辑地址";
    } else {
        self.navigationItem.title = @"添加新地址";
    }
    
    
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem = saveItem;
    
    [self makeConstraints];
}

#pragma mark - Lazy Loading

- (NSArray<NSString *> *)options {
    return @[@"收货人",@"手机号码",@"固定电话",@"所在地区",@"详细地址",@"邮编"];
}

- (UITableView *)infoListView {
    
    if (!_infoListView) {
        
        _infoListView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _infoListView.showsVerticalScrollIndicator = NO;
        _infoListView.showsHorizontalScrollIndicator = NO;
        _infoListView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _infoListView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _infoListView.delegate = self;
        _infoListView.dataSource = self;
        _infoListView.estimatedRowHeight = OPTION_HEIGHT;
        [_infoListView registerNib:[UINib nibWithNibName:@"AddNewAddressOptionTableViewCell" bundle:nil] forCellReuseIdentifier:@"addNewAddressOptionTableViewCell"];
        
        [self.view addSubview:_infoListView];
    }
    return _infoListView;
}

#pragma mark - Layout

- (void)makeConstraints {
    
    [self.infoListView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(20);
        make.left.and.right.equalTo(self.view);
        make.height.mas_equalTo(@(OPTION_HEIGHT*self.options.count));
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.options.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"addNewAddressOptionTableViewCell";
    
    AddNewAddressOptionTableViewCell *optionTableViewCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    optionTableViewCell.titleLabel.text = [self.options objectAtIndex:indexPath.row];
    if (indexPath.row == 3) {
        optionTableViewCell.contentTextField.enabled = NO;
        optionTableViewCell.accessoryLabel.text = @"请选择 >";
    }
    
    if (_model) {
        if (indexPath.row == 0) {
            optionTableViewCell.contentTextField.text = _model.realName;
        } else if (indexPath.row == 1) {
            optionTableViewCell.contentTextField.text = _model.mobile;
        } else if (indexPath.row == 2) {
            optionTableViewCell.contentTextField.text = _model.tel;
        } else if (indexPath.row == 3) {
            optionTableViewCell.contentTextField.text = _model.location;
        } else if (indexPath.row == 4) {
            optionTableViewCell.contentTextField.text = _model.address;
        } else if (indexPath.row == 5) {
            optionTableViewCell.contentTextField.text = _model.zipCode;
        }
    }
    
    
    return optionTableViewCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row != 3) {
        return;
    }
    
    AddNewAddressOptionTableViewCell *cell = [_infoListView cellForRowAtIndexPath:indexPath];
    
    if (self.selectedArr) {
        
        NSArray *defaultValues = @[[self.selectedArr objectAtIndex:0][@"text"],[self.selectedArr objectAtIndex:1][@"text"],[self.selectedArr objectAtIndex:2][@"text"]];
        JYAddressPicker *addressPicker = [JYAddressPicker jy_showAt:self defaultShow:defaultValues];
        addressPicker.selectedItemBlock = ^(NSArray *addressArr) {
            
            NSString *province = [addressArr objectAtIndex:0][@"text"];
            NSString *city = [addressArr objectAtIndex:1][@"text"];
            NSString *county = [addressArr objectAtIndex:2][@"text"];
            
            cell.contentTextField.text = [NSString stringWithFormat:@"%@%@%@",province,city,county];
            self.selectedArr = addressArr;
        };
    }else{
        JYAddressPicker *addressPicker = [JYAddressPicker jy_showAt:self];
        addressPicker.selectedItemBlock = ^(NSArray *addressArr) {
            
            NSString *province = [addressArr objectAtIndex:0][@"text"];
            NSString *city = [addressArr objectAtIndex:1][@"text"];
            NSString *county = [addressArr objectAtIndex:2][@"text"];
            
            cell.contentTextField.text = [NSString stringWithFormat:@"%@%@%@",province,city,county];
            self.selectedArr = addressArr;
        };
        
    }

    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return OPTION_HEIGHT;
}

#pragma mark - Button Action

- (void)save {
    
    NSArray *placeArr = @[@"请输入收货人姓名",
                          @"请输入手机号码",
                          @"请输入固定电话",
                          @"请选择收货地址",
                          @"请输入详细地址",
                          @"请输入邮政编码"];
    NSMutableArray *paramsArr = [NSMutableArray array];
    __block NSInteger count = 0;
    [placeArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
        AddNewAddressOptionTableViewCell *cell = [_infoListView cellForRowAtIndexPath:indexPath];
        NSString *str = cell.contentTextField.text;
        if (_model) {
            if (idx == 0) {
                _model.realName = str;
            } else if (idx == 1) {
                _model.mobile = str;
            } else if (idx == 3) {
                _model.location = str;
            } else if (idx == 4) {
                _model.address = str;
            } else if (idx == 2) {
                _model.tel = str;
            } else if (idx == 5) {
                _model.zipCode = str;
            }
        }
        
        if (str.length == 0) {
            ShowMessage(obj);
            *stop = YES;
        } else {
            
            [paramsArr addObject:str];
            count++;
        }

    }];
    
    if (count !=  placeArr.count) {
        return;
    }
    
    if (_model) {
        bool bool_true = true;
        bool bool_false = false;
        
        _model.isDefault = @(bool_false);
        _model.isEditOrNew = @(bool_false);
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:_model.mj_JSONObject];
        [params removeObjectForKey:@"userName"];
        
        NSDictionary *param = @{@"delivery": @"5",
                                @"isEdit": @(bool_true),
                                @"siteId": @"32",
                                @"addressInfo":params
                                };
        
        [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiPaySaveAddress" params:param.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
            ShowMessage(@"修改成功");
            [self.navigationController popViewControllerAnimated:YES];

        } failure:^{
            
        }];

    } else {
        NSDictionary *paramDic = @{@"addressInfo":@{@"realName":paramsArr[0],
                                                    @"mobile":paramsArr[1],
                                                    @"tel":paramsArr[2],
                                                    @"location":paramsArr[3],
                                                    @"address":paramsArr[4],
                                                    @"zipCode":paramsArr[5],
                                                    @"isDefault":@0,
                                                    @"isEditOrNew":@0
                                                    },
                                   @"delivery":@"5",
                                   @"isEdit":@0,
                                   @"siteId":@"32"
                                   };
        
        [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiPaySaveAddress" params:paramDic.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
            ShowMessage(@"添加成功");
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^{
            
        }];
    }
    
    
    
    
}

#pragma mark - Memory Warning

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
